const { db } = require('./DbService');
const _ = db.command;
function getRandomInt(max) {
  return Math.floor(Math.random() * max) + 1;
}

// 生成用户 ID
function generateUserId() {
	const now = new Date();
	const dateString = now.toISOString().replace(/[^0-9]/g, '').slice(0, 14); // YYYYMMDDHHmmSS
	const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0'); // 生成六位随机数字
	return "U" + dateString + randomNum; // 拼接结果
  }

// 生成砍价记录 ID
function generateBargainId() {
	const now = new Date();
	const dateString = now.toISOString().replace(/[^0-9]/g, '').slice(0, 14); // YYYYMMDDHHmmSS
	const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0'); // 生成六位随机数字
	return "B" + dateString + randomNum; // 拼接结果
}

// 转换元到角
function convertYuanToJiao(input) {
	const yuan = typeof input === 'string' ? parseFloat(input) : input;
	if (isNaN(yuan)) {
		throw new Error('Invalid input: not a number');
	}
	return Math.round(yuan * 10); // 转换为角
}

// 转换角到元字符串
function convertJiaoToYuanString(jiao) {
	if (typeof jiao !== 'number') {
		throw new Error('Invalid input: not an integer');
	}
	return (jiao / 10).toFixed(1); // 转换为元，保留一位小数
}

async function computeAllowedBargainAmount(productId, bargainConfig) {
	const totalVaildBargainToday = await queryTodayVaildBargainCnt(productId);
	const allowPriceArr = bargainConfig.allow_pirce_arr;
	allowPriceArr.sort((a, b) => b.total - a.total);
	for (let i = 0; i < allowPriceArr.length; i++) {
		const allowPrice = allowPriceArr[i];
		if (totalVaildBargainToday >= allowPrice.total) {
			return allowPrice.allow;
		}
	}
	return 0;
}
async function queryTodayVaildBargainCnt(productId) {
	const today = new Date();
	today.setHours(0, 0, 0, 0);
	const tomorrow = new Date(today);
	tomorrow.setDate(tomorrow.getDate() + 1);
	const res = await db.collection('bargain_record').where({
		product_id: productId,
		create_ts: _.gt(today).and(_.lt(tomorrow))
	}).count();
	return res.total;
}

async function getBargainRecord(participantId) {
	let bargainRecord = null;
	if (!participantId) {
		return bargainRecord;
	}
	const bargainRes = await db.collection('bargain_record').where({
		participant_id: participantId,
	}).get();
	if (bargainRes.data.length > 0) {
		bargainRecord = bargainRes.data[0];
	}
	return bargainRecord;
}

async function getBargainDetails(participantId) {
	const bargainDetailsRes = await db.collection('bargain_detail').where({ participant_id: participantId }).get();
	return bargainDetailsRes.data;
}

async function getProduct(productId) {
	// 获取产品信息
	let product = null;
	const productRes = await db.collection('product').where({ product_id: productId }).get();
	if (productRes.data.length > 0) {
		product = productRes.data[0];
	}
	return product;
}

function getNoticeText(bargainRecord, bargainConfig) {
	if (!bargainRecord.allow_amount) {
		return null;
	}
	const allowPriceArr = bargainConfig.allow_pirce_arr;
	allowPriceArr.sort((a, b) => b.allow - a.allow);
	for (let i = 0; i < allowPriceArr.length; i++) {
		const allowPrice = allowPriceArr[i];
		if (bargainRecord.allow_amount >= allowPrice.allow) {
			return allowPrice.notice_text;
		}
	}
	return null;
}

function getRandomAvatar() {
	const random = Math.random();
	return random < 0.5 ? "https://7072-prod-3gjcorog35addaa7-1348173015.tcb.qcloud.la/bargain/0_default_person_head.png?sign=70f6ff2903d9b36c59855123677b3b89&t=1742572662" : "https://7072-prod-3gjcorog35addaa7-1348173015.tcb.qcloud.la/bargain/0_mine_person_pic2.png?sign=a755eb717264bf8fe3af56d95af4fc3d&t=1742572709";
}

function convertToRelativeTime(helpTime) {
	const currentDate = new Date(); // 当前时间
	const diff = currentDate - helpTime; // 时间差（单位：毫秒）

	const minutes = Math.floor(diff / (1000 * 60)); // 毫秒转换为分钟
	const hours = Math.floor(diff / (1000 * 60 * 60)); // 毫秒转换为小时
	const days = Math.floor(diff / (1000 * 60 * 60 * 24)); // 毫秒转换为天

	if (minutes < 1) {
		return "刚刚";
	} else if (minutes < 59) {
		return `${minutes}分钟前`;
	} else if (hours < 23) {
		return `${hours}小时前`;
	} else {
		return `${days}天前`;
	}
}

async function createBargain(request) {
	const {
		openId, productId, quantity
	} = request;

	if (!productId || !quantity) {
		console.error("Invalid parameters");
		throw new Error('Invalid parameters');
	}

	// 并行查询用户信息、商品信息和砍价记录
	const [userRes, productRes, bargainRecordRes, bargainConfigRes] = await Promise.all([
		db.collection('user').where({
			out_user_id: openId
		}).get(),
		db.collection('product').where({
			product_id: productId
		}).get(),
		db.collection('bargain_record').where({
			out_user_id: openId,
			product_id: productId
		}).get(),
		db.collection('config').where({
			config_name: "bargain_config",
			product_id: productId
		}).get(),
	]);

	// 检查用户信息
	if (userRes.data.length === 0) {
		console.error("User not found", "userId:", openId);
		throw new Error('User not found');
	}

	// 检查商品信息
	if (productRes.data.length === 0) {
		console.error("Product not found", "productId:", productId);
		throw new Error('Product not found');
	}

	const productCloud = productRes.data[0];
	const bargainRecords = bargainRecordRes.data;

	// 检查是否有进行中的砍价
	const progressingBargain = bargainRecords.find((record) => record.status === 'progressing'
		&& record.deadline && record.deadline.getTime() > new Date().getTime());
	if (progressingBargain) {
		// 查询砍价详情
		const bargainDetailsRes = await db
			.collection('bargain_detail')
			.where({
				participant_id: progressingBargain.participant_id
			})
			.get();

		// 计算已砍掉金额
		const reducedAmount = bargainDetailsRes.data.reduce((sum, item) => {
			const helpPriceInJiao = convertYuanToJiao(item.help_price); // 转换为角
			return sum + helpPriceInJiao;
		}, 0);

		const reduceAmountStr = convertJiaoToYuanString(reducedAmount);
		return {
			code: 200,
			message: 'Bargain record found',
			data: {
				participantId: progressingBargain.participant_id,
				totalAmount: progressingBargain.amount,
				reducedAmount: reduceAmountStr,
			},
		};
	}

	// 创建新的砍价记录
	const totalAmount = convertYuanToJiao(productCloud.price) * quantity;
	const totalAmountStr = convertJiaoToYuanString(totalAmount);
	const allowAmount = await computeAllowedBargainAmount(productId, bargainConfigRes.data[0]);

	const now = new Date();
	const newRecord = {
		create_ts: now,
		update_ts: now,
		participant_id: generateBargainId(),
		status: 'progressing',
		out_user_id: openId,
		product_id: productId,
		quantity,
		amount: totalAmountStr,
		allow_amount: allowAmount,
		deadline: new Date(now.getTime() + 48 * 60 * 60 * 1000)
	};

	await db.collection('bargain_record').add({
		data: newRecord,
	});

	return {
		code: 200,
		message: 'Bargain record created',
		data: {
			participantId: newRecord.participant_id,
			totalAmount: totalAmountStr,
			reducedAmount: '0.0',
		},
	}
}

async function helpBargain(request) {
	const {
		openId, participantId
	} = request;
	// 查询用户信息
	const userRecordRes = await db.collection('user').where({
		out_user_id: openId
	}).get()

	// 如果是新用户，创建用户信息
	if (!userRecordRes || userRecordRes.data.length == 0) {
		const newUser = {
			user_id: generateUserId(), // 生成一个唯一的 user_id
			out_user_id: openId,
			role_type: ['user'],
			ext_info: {
				address: [],
			},
			create_ts: new Date()
		}
		await db.collection('user').add({
			data: newUser
		})
	}

	let [bargainRecordRes, bargainDetailsRes] = await Promise.all([
		db.collection('bargain_record').where({ participant_id: participantId }).get(),
		db.collection('bargain_detail').where({ participant_id: participantId }).get(),
	]);
	if (bargainRecordRes.data.length === 0) {
		return {
			code: 404,
			message: "bargain not found",
		}
	}
	const bargainRecord = bargainRecordRes.data[0];
	if (bargainRecord.out_user_id === openId) {
		return {
			code: 406,
			message: "不能帮自己砍哦~"
		}
	}

	//砍价明细
	let bargainDetails = [];
	if (bargainDetailsRes && bargainDetailsRes.data) {
		bargainDetails = bargainDetailsRes.data;
	}
	const userHelpDetail = bargainDetails.find(item => item.help_out_user_id == openId);
	if (userHelpDetail) {
		return {
			code: 406,
			message: "已经帮忙砍过价啦~"
		}
	}

	const [bargainConfigRes] = await Promise.all([
		db.collection('config').where({
			config_name: "bargain_config",
			product_id: bargainRecord.product_id
		}).get(),
	]);
	const avgBargainPrice = bargainConfigRes.data[0].avg_bargain_price;
	const maxNumToFinish = bargainConfigRes.data[0].max_num_finish;
	const totalAmountCanBargain = convertYuanToJiao(bargainRecord.amount);
	const allowAmount = bargainRecord.allow_amount || 9999;
	const amountHasBargained = bargainDetails.reduce((acc, cur) => {
		return acc += convertYuanToJiao(cur.help_price)
	}, 0)
	const amountLeft = Math.min(allowAmount, totalAmountCanBargain) - amountHasBargained;
	if (amountLeft <= 0) {
		return {
			code: 406,
			message: "砍价完成了，不需要砍啦~"
		}
	}
	let bargainAmount = 0;
	if (bargainDetails.length >= maxNumToFinish - 1) {
		bargainAmount = amountLeft;
	} else {
		bargainAmount = Math.min(getRandomInt(avgBargainPrice * 2), 30, amountLeft);
	}
	const bargainAmountStr = convertJiaoToYuanString(bargainAmount);
	const amoutLeftAfterBargain = amountLeft - bargainAmount;
	const amoutLeftAfterBargainStr = convertJiaoToYuanString(amoutLeftAfterBargain);
	newBargainDetail = {
		create_ts: new Date(),
		update_ts: new Date(),
		participant_id: participantId,
		help_out_user_id: openId,
		help_price: bargainAmountStr,
		out_user_id: bargainRecord.out_user_id
	}

	// 插入新的砍价记录
	const insertRes = await db.collection('bargain_detail').add({
		data: newBargainDetail
	});

	return {
		code: 200,
		message: "帮忙朋友猛砍" + bargainAmountStr + "元",
		data: {
			"reduceAmount": bargainAmountStr,
			"remainingAmount": amoutLeftAfterBargainStr
		}
	}
}

async function getBargainDetail(request) {
	const {
		participantId
	} = request;
	// 获取砍价活动记录
	const bargainRecord = await getBargainRecord(participantId);
	if (!bargainRecord) {
		console.error("未找到砍价活动记录", participantId);
		return {
			code: 406,
			message: "未找到砍价活动信息",
		};
	}

	const bargainTotalAmountStr = bargainRecord.amount; // 总金额（元）
	const productQty = bargainRecord.quantity; // 商品数量

	// 获取砍价详情
	const bargainDetails = await getBargainDetails(participantId);

	// 计算总折扣金额（所有参与者砍掉的金额总和）
	const bargainDiscount = bargainDetails.reduce((sum, item) => {
		const helpPriceInJiao = convertYuanToJiao(item.help_price); // 转换为角
		return sum + helpPriceInJiao;
	}, 0);
	const bargainDiscountStr = convertJiaoToYuanString(bargainDiscount); // 折扣金额（元）

	// 获取参与者及其砍价金额
	const participantsVo = bargainDetails.map((item) => {
		return {
			helperId: item.help_out_user_id, // 帮助砍价的用户 ID
			helpedPrice: item.help_price, // 该用户砍掉的金额（元）
			avatar: getRandomAvatar(),
			nickName: item.help_out_user_id.substr(-4), // 参与者的名字（如果有）
			helpTime: convertToRelativeTime(item.create_ts), // 砍价时间
		};
	});

	// 获取商品信息
	const product = await getProduct(bargainRecord.product_id);
	if (!product) {
		console.error("未找到砍价活动对应的产品信息", bargainRecord.product_id);
		return {
			code: 406,
			message: "未找到砍价活动对应的产品信息",
		};
	}
	const productImg = product.image_url; // 商品图片
	const productPrice = product.price; // 商品单价

	// 并行查询用户信息、商品信息和砍价记录
	const [bargainConfigRes] = await Promise.all([
		db.collection('config').where({
			config_name: "bargain_config",
			product_id: product.product_id
		}).get(),
	]);
	const bargainConfig = bargainConfigRes.data[0];
	const noticeText = getNoticeText(bargainRecord, bargainConfig);
	const shareTitle = bargainConfig.share_title;
	const shareDesc = bargainConfig.share_desc;
	const shareImg = bargainConfig.share_image;

	// 计算应付金额
	const payAmount = convertYuanToJiao(bargainTotalAmountStr) - bargainDiscount;
	const timeLeftMills = Math.max(bargainRecord.deadline.getTime() - new Date().getTime(), 0);
	return {
		code: 200,
		message: timeLeftMills <= 0 ? "砍价活动已结束,请重新参加活动" : "success",
		data: {
			participantId: participantId,
			productId: product.product_id,
			productTitle: product.product_title,
			totalAmount: bargainTotalAmountStr, // 总金额
			reducedAmount: bargainDiscountStr, // 已砍掉的金额
			allowBargainAmount: bargainRecord.allow_amount,
			price: productPrice, // 商品单价
			quantity: productQty, // 商品数量
			payAmount: convertJiaoToYuanString(payAmount), // 应付金额
			imageUrl: productImg, // 商品图片
			helperRankList: participantsVo, // 参与者列表
			timeLeft: Math.floor(timeLeftMills / 1000), // 剩余时间（毫秒）,
			noticeText: noticeText, // 提示文本
			shareTitle: shareTitle,
			shareDesc: shareDesc,
			shareImg: shareImg,
		},
	};
}

module.exports = {
	createBargain:createBargain,
  helpBargain:helpBargain,
  getBargainDetail:getBargainDetail
}